class_name Modifier
extends Node

enum Type {DMG_DEALT, DMG_TAKEN, CARD_COST, SHOP_COST, NO_MODIFIER, CARD_EFFECT_MULTIPLIER}

@export var type: Type


func get_value(source: String) -> ModifierValue:
	for value: ModifierValue in get_children():
		if value.source == source:
			return value
		
	return null


func add_new_value(value: ModifierValue) -> void:
	print("🔧 Modifier.add_new_value: 添加修改器值 source=%s, type=%s" % [value.source, value.type])
	var modifier_value := get_value(value.source)
	if not modifier_value:
		print("🔧 创建新的修改器值")
		add_child(value)
		print("🔧 新修改器值已添加为子节点")
	else:
		print("🔧 更新现有修改器值: flat_value %d → %d, percent_value %.1f → %.1f" % [
			modifier_value.flat_value, value.flat_value,
			modifier_value.percent_value, value.percent_value
		])
		modifier_value.flat_value = value.flat_value
		modifier_value.percent_value = value.percent_value
		print("🔧 现有修改器值已更新")
	
	# 验证添加结果
	var final_value = get_value(value.source)
	if final_value:
		print("✅ 修改器值添加成功: source=%s, flat_value=%d, percent_value=%.1f" % [
			final_value.source, final_value.flat_value, final_value.percent_value
		])
	else:
		print("❌ 修改器值添加失败")


func remove_value(source: String) -> void:
	for value: ModifierValue in get_children():
		if value.source == source:
			value.queue_free()


func clear_values() -> void:
	for value: ModifierValue in get_children():
		value.queue_free()


func get_modified_value(base: int) -> int:
	var flat_result: int = base
	var percent_result: float = 1.0
	print("🔧 Modifier.get_modified_value: 基础值=%d, 类型=%s" % [base, type])
	
	# Apply flat modifiers first
	for value: ModifierValue in get_children():
		if value.type == ModifierValue.Type.FLAT:
			flat_result += value.flat_value
			print("🔧 应用FLAT修改器: source=%s, flat_value=%d, 结果=%d" % [value.source, value.flat_value, flat_result])
	
	# Apply % modifiers next
	for value: ModifierValue in get_children():
		if value.type == ModifierValue.Type.PERCENT_BASED:
			percent_result += value.percent_value
			print("🔧 应用PERCENT修改器: source=%s, percent_value=%.1f, 结果=%.1f" % [value.source, value.percent_value, percent_result])
	
	var final_result = floori(flat_result * percent_result)
	print("🔧 Modifier.get_modified_value: 最终结果=%d (flat=%d * percent=%.1f)" % [final_result, flat_result, percent_result])
	return final_result
